package com.comcast.eep.bridge.common;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Arrays;
import java.util.List;
import java.util.zip.InflaterInputStream;

import javax.jms.BytesMessage;
import javax.jms.JMSException;

public class EEPBridgeUtils {

	private final static int DEFAULT_BUFFER_SIZE = 1024 * 10;
	
	public static List<String> trimConsumer(String consumer){
		consumer = consumer.substring(1, consumer.length() -1);
		return Arrays.asList(consumer.split("__"));
	}
	
    public static byte[] getRawData(BytesMessage bm) throws JMSException {
        byte[] rawBytes = new byte[DEFAULT_BUFFER_SIZE];
        int result = 0;
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        do {
            result = bm.readBytes(rawBytes);
            if (result != -1) {
                bos.write(rawBytes, 0, result);
            }
        } while (result != -1);
        return bos.toByteArray();
    }
    
    public static byte[] decompressData(byte[] data) throws IOException {
        if (data == null) {
            return null;
        }
        
        ByteArrayOutputStream baos = null;
        ByteArrayInputStream bais = null;
        InflaterInputStream iin = null;
        try {
            //result container
            baos = new ByteArrayOutputStream(data.length * 2); 
            bais = new ByteArrayInputStream(data);
            iin = new InflaterInputStream(bais);
            //read data out using buffer
            byte[] buf = new byte[1024];  
            int len = 0; 
            while ((len = iin.read(buf)) > 0) {  
                baos.write(buf, 0, len);  
            }   
            return baos.toByteArray();  
        } finally {
            close(iin);
            close(bais);
            close(baos);
        } 
    } 
    
    private static void close(InputStream input) {
        try {
            if (input != null) {
                input.close();
            }
        } catch (Exception e) {             
        }
    }
    
    private static void close(OutputStream output) {
        try {
            if (output != null) {
                output.close();
            }
        } catch (Exception e) { 
        }
    } 
}
